<?php
App::uses('AppModel', 'Model');

class Usuario extends AppModel {

	public $displayField = 'nome';
	public $validate = array(
		'nome' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
		),
		'email' => array(
			'email' => array(
				'rule' => array('email'),
			),
			'unique' => array(
				'rule'=>array('isUnique'),
			),
		),
		'senha' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
			'senhas_diferentes'=>array(
				'rule' => 'senhasIguais'
			)
			
		),
		'confirmar_senha'=>array(
			'notempty' => array(
				'rule'=>array('notempty')
			),
		),
		'reviews' => array(
			'numeric' => array(
				'rule' => array('numeric'),
			),
		),
		'nota_media' => array(
			'decimal' => array(
				'rule' => array('decimal'),
			),
		),
		'apelido' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
			'unique' => array(
				'rule'=>array('isUnique'),
			),
		),
		
	);

	public $hasMany = array(
		'Review' => array(
			'className' => 'Review',
			'foreignKey' => 'usuario_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);
	
	public function senhasIguais($data){
        if(!isset($this->data['Usuario']['confirmar_senha']) || $data['senha'] == $this->data['Usuario']['confirmar_senha'])
                return true;
        $this->invalidate('confirmar_senha', 'senhas_diferentes');
        return false;
    }
    
    public function beforeSave(){
    	if(isset($this->data['Usuario']['senha_hash']))
    		$this->data['Usuario']['senha'] = $this->data['Usuario']['senha_hash'];
    	if(isset($this->data['Usuario']['id']))
    		unset($this->data['Usuario']['senha']);
    	return true;
    }
    
    public function ativarConta($hash){
    	$this->recursive = -1;
    	$result = $this->findBySecurityHash($hash);
    	if(empty($result))
    		return false;
    	else if($result['Usuario']['ativo'] == 1)
    		return false;
    	else{
    		$result['Usuario']['ativo'] = 1;
    		if($this->save($result))
    			return true;
    	}
    }
}
